package com.controller;

import com.entity.appCategory;
import com.entity.appInfo;
import com.entity.appVersion;
import com.entity.devUser;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.service.developerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

@Controller
public class developerController {
    @Autowired
    developerService developerService;

    /**
     * 开发者平台登录
     *
     * @param devName
     * @param devPassword
     * @param request
     * @return
     */
    @RequestMapping("/devLogin")
    public ModelAndView devLogin(String devName, String devPassword, HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView();
        devUser devUser = developerService.devLogin(devName, devPassword);
        String mess = "";
        if (devUser != null) {
//            保存用户名和密码
            request.getSession().setAttribute("devUser", devUser);
            modelAndView.addObject("devUser", devUser);
//            进入到登录成功后的页面
            modelAndView.setViewName("/mainDeveloper");
        } else {
            mess = "用户名或密码错误，请重新输入！！";
            modelAndView.addObject("mess", mess);
            modelAndView.setViewName("/loginDeveloper");
        }
        return modelAndView;
    }

    /**
     * 开发者平台注册
     */
    @RequestMapping("/devRegister")
    public ModelAndView devRegister(String devName, String uEmail, String uPwd, String uIntroduce) {
        ModelAndView modelAndView = new ModelAndView();
        devUser devUser = new devUser();
        devUser.setDevCode(devName);
        devUser.setDevName(devName);
        devUser.setDevPassword(uPwd);
        devUser.setDevEmail(uEmail);
        devUser.setDevInfo(uIntroduce);
        devUser.setCreatedBy(1);
        Date date = new Date();
        devUser.setCreationDate(date);
        int i = developerService.devRegister(devUser);
        if (i > 0) {
            modelAndView.setViewName("redirect:/jsp/loginDeveloper.jsp");
        }
        return modelAndView;
    }

    /**
     * 开发者注册时，其账号不能重复，所以要查询数据库中是否有开发者输入的账号
     */
    @RequestMapping("/judgeDevCode")
    @ResponseBody
    public int judgeDevCode(String devName) {
        int i = 0;
        if (devName != null && !"".equals(devName)) {
            i = developerService.judgeDevCode(devName);
        } else {
            i = -1;
        }
        return i;
    }

    /**
     * 用户退出
     */
    @RequestMapping("/signOut")
    public ModelAndView signOut(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView();
        request.getSession().invalidate();
        modelAndView.setViewName("/loginDeveloper");
        return modelAndView;
    }

    /**
     * 分页展示app内容，并可以根据条件查询
     */
    @RequestMapping("/devShow")
    public ModelAndView devShow(String softwareName, String status, String flatForm, Integer categoryName1,
                                Integer categoryName2, Integer categoryName3, @RequestParam(defaultValue = "1", value = "pageIndex") Integer pageIndex) {
        ModelAndView modelAndView = new ModelAndView();
        PageHelper.startPage(pageIndex, 5);
        List<appInfo> appInfoList = developerService.devShow(softwareName, status, flatForm, categoryName1, categoryName2, categoryName3);
        PageInfo<appInfo> pageInfo = new PageInfo<>(appInfoList);
        modelAndView.addObject("pageInfo", pageInfo);
        modelAndView.addObject("appInfoList", appInfoList);
        modelAndView.addObject("softwareName",softwareName);
        modelAndView.addObject("status",status);
        modelAndView.addObject("flatForm",flatForm);
        modelAndView.addObject("categoryName1",categoryName1);
        modelAndView.addObject("categoryName2",categoryName2);
        modelAndView.addObject("categoryName3",categoryName3);
        modelAndView.setViewName("/maintainDeveloper");
        return modelAndView;
    }

    /**
     * 根据用户输入的一二级分类，查找二三级分类
     */
    @RequestMapping("/findSort")
    @ResponseBody
    public List<appCategory> findSort(Integer categoryNameAll) {
        return developerService.findSort(categoryNameAll);
    }

    /**
     * 新增app信息
     */
    @RequestMapping("/addAppInfor")
    public ModelAndView addAppInfor(String softwareName, String APKName, String rom, String language, Integer appSize, Integer downloads, Integer flatForm, Integer categoryName1,
                                    Integer categoryName2, Integer categoryName3, String textarea, MultipartFile logo, HttpSession session, HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView();
        appInfo appInfo = new appInfo();
        appInfo.setSoftwareName(softwareName);
        appInfo.setAPKName(APKName);
        appInfo.setSupportROM(rom);
        appInfo.setInterfaceLanguage(language);
        appInfo.setSoftwareSize(appSize);
//        获取保存的devUser，并获取到其id
        devUser devUser = (com.entity.devUser) session.getAttribute("devUser");
        appInfo.setDevId(devUser.getId());
        appInfo.setAppInfo(textarea);
        appInfo.setStatus(1);
        appInfo.setFlatformId(flatForm);
        appInfo.setDownloads(downloads);
        appInfo.setCategoryLevel1(categoryName1);
        appInfo.setCategoryLevel2(categoryName2);
        appInfo.setCategoryLevel3(categoryName3);
        appInfo.setCreatedBy(devUser.getId());
//        创建日期
        Date date = new Date();
        appInfo.setCreationDate(date);
//        获取文件名
        String filename = logo.getOriginalFilename();
//        保存文件的路径
        String path = request.getServletContext().getRealPath("/img/");
//        生成一个目录文件
        File file = new File(path, filename);
//        如果目录文件不存在，就把它创建出来
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
//        将文件保存到目录中
        try {
            logo.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
//        在数据库中加入logo路径
        appInfo.setLogoLocPath(path);
        int i = developerService.addAppInfor(appInfo);
        if (i > 0) {
            modelAndView.setViewName("redirect:/devShow");
        } else {
            modelAndView.setViewName("addAppInformation");
        }
        return modelAndView;
    }

    /**
     * 验证APKName不能重复
     */
    @RequestMapping("/judgeAPKName")
    @ResponseBody
    public int judgeAPKName(String APKName) {
        int i = 0;
        if (APKName != null && APKName != "") {
            i = developerService.judgeAPKName(APKName);
        } else {
            i = -1;
        }
        return i;
    }

    /**
     * 修改app，先根据id获取app的内容
     */
    @RequestMapping("/modifyFindApp")
    public ModelAndView modifyFindApp(Integer id) {
        ModelAndView modelAndView = new ModelAndView();
        appInfo appInfo = developerService.modifyFindApp(id);
        modelAndView.addObject(appInfo);
        modelAndView.setViewName("modifyApp");
        return modelAndView;
    }

    /**
     * 根据app_info表的status查找app状态
     */
    @RequestMapping("/findFlatForm")
    @ResponseBody
    public List<appInfo> findFlatForm() {
        Integer flatFormId = null;
        List<appInfo> flatForm = developerService.findFlatForm(flatFormId);
        return flatForm;
    }

    /**
     * 根据app_info表的categoryLevel3查找其所在父类的所有分类
     */
    @RequestMapping("/findCategoryName3")
    @ResponseBody
    public List<appCategory> findCategoryName3(Integer id) {
        List<appCategory> categoryName3 = developerService.findCategoryName3(id);
        return categoryName3;
    }

    /**
     * 修改app，下载图片
     */
    @RequestMapping("/downLoad")
    public void downLoad(String fileName, HttpServletRequest request, HttpServletResponse response) throws IOException {
//        下载地址
        String path = request.getServletContext().getRealPath("/img/");
//        设置response响应头
        response.reset(); //清空页面缓存
        response.setCharacterEncoding("UTF-8"); //设置字符集
        response.setContentType("multipart/form-data"); //设置下载的类型，二进制传输
        response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "utf-8")); //响应头
        File file = new File(path, fileName);

//        读取文件
        InputStream input = new FileInputStream(file);
//        写出文件
        OutputStream out = response.getOutputStream();

        byte[] buff = new byte[1024];
        int index = 0;
//        执行写出操作
        while ((index = input.read(buff)) != -1) {
            out.write(buff, 0, index);
            out.flush();
        }
        out.close();
        input.close();
    }

    /**
     * 修改app信息
     */
    @RequestMapping("/modifyApp")
    public ModelAndView modifyApp(String softwareName, String APKName, String rom, String language, Integer appSize, Integer downloads, Integer flatForm, Integer categoryName1,
                                  Integer categoryName2, Integer categoryName3, String textarea, MultipartFile logo, Integer id, HttpSession session, HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView();
        appInfo appInfo = new appInfo();
        appInfo.setId(id);
        appInfo.setSoftwareName(softwareName);
        appInfo.setAPKName(APKName);
        appInfo.setSupportROM(rom);
        appInfo.setInterfaceLanguage(language);
        appInfo.setSoftwareSize(appSize);
//        获取保存的devUser，并获取到其id
        devUser devUser = (com.entity.devUser) session.getAttribute("devUser");
        appInfo.setDevId(devUser.getId());
        appInfo.setAppInfo(textarea);
        appInfo.setStatus(1);
        appInfo.setFlatformId(flatForm);
        appInfo.setDownloads(downloads);
        appInfo.setCategoryLevel1(categoryName1);
        appInfo.setCategoryLevel2(categoryName2);
        appInfo.setCategoryLevel3(categoryName3);
        //        获取文件名
        String filename = logo.getOriginalFilename();
//        保存文件的路径
        String path = request.getServletContext().getRealPath("/img/");
//        生成一个目录文件
        File file = new File(path, filename);
//        如果目录文件不存在，就把它创建出来
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
//        将文件保存到目录中
        try {
            logo.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
//        在数据库中加入logo路径
        appInfo.setLogoLocPath(path);
        int i = developerService.appModify(appInfo);
        String mess;
        if (i > 0) {
            modelAndView.setViewName("redirect:/devShow");
        } else {
            mess = "修改失败，请重新修改";
            modelAndView.addObject("mess", mess);
            modelAndView.setViewName("modifyApp");
        }
        return modelAndView;
    }

    /**
     * 查看历史版本信息
     */
    @RequestMapping("/appVersionShow")
    public ModelAndView appVersionShow(Integer appId) {
        ModelAndView modelAndView = new ModelAndView();
        List<appVersion> appVersionList = developerService.appVersionShow(appId);
        if (appVersionList != null) {
            modelAndView.addObject("appId", appId);
            modelAndView.addObject("appVersionList", appVersionList);
        } else {
            String mess = "该app没有历史版本";
            modelAndView.addObject("mess", mess);
        }
        modelAndView.setViewName("appVersionInformation");
        return modelAndView;
    }

    /**
     * 新增版本信息
     */
    @RequestMapping("/addAppVersion")
    public ModelAndView addAppVersion(Integer appId, String versionNo, Integer versionSize, String textarea, MultipartFile apkFile, HttpSession session, HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView();
        appVersion appVersion = new appVersion();
        appVersion.setAppId(appId);
        appVersion.setVersionNo(versionNo);
        appVersion.setVersionInfo(textarea);
        appVersion.setPublishStatus(3);
        appVersion.setVersionSize(versionSize);
        devUser devUser = (com.entity.devUser) session.getAttribute("devUser");
        appVersion.setCreatedBy(devUser.getId());
        Date date = new Date();
        appVersion.setCreationDate(date);
        //        获取文件名
        String filename = apkFile.getOriginalFilename();
//        保存文件的路径
        String path = request.getServletContext().getRealPath("/file/");
//        生成一个目录文件
        File file = new File(path, filename);
//        如果目录文件不存在，就把它创建出来
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
//        将文件保存到目录中
        try {
            apkFile.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        appVersion.setApkLocPath(path);
        appVersion.setApkFileName(filename);
        int i = developerService.addAppVersion(appVersion);
        String msg;
        if (i > 0) {
//            传入appId，修改app_info表的最新版本号
            modelAndView.addObject("appId",appId);
            modelAndView.setViewName("maintainDeveloper");
        } else {
            msg = "添加失败，请重新添加";
            modelAndView.addObject("msg", msg);
            modelAndView.setViewName("appVersionInformation");
        }
        return modelAndView;
    }

    /**
     * 如果新增版本信息成功，则修改app_Info表的最新版本号id
     */
    @RequestMapping("/modifyVersionId")
    @ResponseBody
    public int modifyVersionId(Integer appId) {
        int i;
        if (appId != null) {
            i = developerService.modifyVersionId(appId);
        } else {
            i = -1;
        }
        return i;
    }

    /**
     * 修改最新版本信息，首先获取最新版本信息
     */
    @RequestMapping("/findAppVersion")
    public ModelAndView findAppVersion(Integer appId){
        ModelAndView modelAndView = new ModelAndView();
        appVersion appVersion = developerService.findAppVersion(appId);
        List<appVersion> versionList = developerService.appVersionShow(appId);
        modelAndView.addObject("versionList",versionList);
        modelAndView.addObject("appId",appId);
        modelAndView.addObject("appVersion",appVersion);
        modelAndView.setViewName("modifyAppVersion");
        return modelAndView;
    }

    /**
     * 修改最新版本信息
     */
    @RequestMapping("/modifyAppVersion")
    public ModelAndView modifyAppVersion(Integer id,String textarea,Integer versionSize,MultipartFile apkFile,Integer appId,HttpSession session,HttpServletRequest request){
        ModelAndView modelAndView = new ModelAndView();
        appVersion appVersion = new appVersion();
        appVersion.setId(id);
        appVersion.setVersionInfo(textarea);
        appVersion.setVersionSize(versionSize);
        devUser devUser = (com.entity.devUser) session.getAttribute("devUser");
        appVersion.setModifyBy(devUser.getId());
        Date date = new Date();
        appVersion.setModifyDate(date);
        //        获取文件名
        String filename = apkFile.getOriginalFilename();
//        保存文件的路径
        String path = request.getServletContext().getRealPath("/file/");
//        生成一个目录文件
        File file = new File(path, filename);
//        如果目录文件不存在，就把它创建出来
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
//        将文件保存到目录中
        try {
            apkFile.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        appVersion.setApkLocPath(path);
        appVersion.setApkFileName(filename);
        int i = developerService.modifyAppVersion(appVersion);
        String mess;
        if (i > 0){
            modelAndView.setViewName("redirect:/devShow");
        }else {
            mess="修改失败";
            List<appVersion> versionList = developerService.appVersionShow(appId);
            modelAndView.addObject("versionList",versionList);
            modelAndView.addObject("mess",mess);
            modelAndView.setViewName("modifyAppVersion");
        }
        return modelAndView;
    }

    /**
     * 查看app信息
     */
    @RequestMapping("/seeApp")
    public ModelAndView seeApp(Integer id){
        ModelAndView modelAndView = new ModelAndView();
        appInfo appInfo = developerService.modifyFindApp(id);
        modelAndView.addObject(appInfo);
        List<appVersion> appVersionList = developerService.appVersionShow(id);
        modelAndView.addObject("appVersionList",appVersionList);
        modelAndView.setViewName("seeApp");
        return modelAndView;
    }

    /**
     * 根据id，删除app基本信息以及所有版本信息
     */
    @RequestMapping("/deleteApp")
    @ResponseBody
    public int deleteApp(Integer id){
        int i ;
        if (id != null){
            i = developerService.deleteApp(id);
        }else {
            i = -1;
        }
        return i;
    }

    /**
     * app上架
     */
    @RequestMapping("/putOnApp")
    @ResponseBody
    public int putOnApp(Integer id){
        int i=0;
        if (id != null){
            i = developerService.putOnApp(id);
        }else {
            i =-1;
        }
        return i;
    }

    /**
     * app下架
     */
    @RequestMapping("/offOnApp")
    @ResponseBody
    public int offOnApp(Integer id){
        int i=0;
        if (id != null){
            i = developerService.offOnApp(id);
        }else {
            i =-1;
        }
        return i;
    }
}
